package zhongbo.java.air.monitor.web.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

/**
 * @ClassName AlertZoneWebSocket
 * @Description TODO
 * @Author 琪
 * @Date 2025/4/9 09:31
 */
@ServerEndpoint(value = "/websocket/alert")
@Component
@Slf4j
public class AlertZoneWebSocket {
    private static final Set<Session> sessions = Collections.synchronizedSet(new HashSet<>());

    @OnOpen
    public void onOpen(Session session) {  String sessionId = session.getId();
        System.out.printf("关闭ws连接: %s, 当前连接数: %d", sessionId, sessions.size());
        sessions.add(session);
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        // 处理WebSocket消息接收逻辑
    }

    @OnClose
    public void onClose(Session session) {
        // 处理WebSocket连接关闭逻辑
    }

    public void broadcastMessage(String message) {
        // 广播消息给所有在线用户
        sessions.forEach(session -> {
            if (session.isOpen()) {
                System.out.println("收到ws消息 = " + message);
                try {
                    session.getBasicRemote().sendText(message);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
